package com.wyx.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyx.Common.Basecontext;
import com.wyx.Common.R;
import com.wyx.Dao.OrdersDao;
import com.wyx.Pojo.*;
import com.wyx.Service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrdersServiceimpl extends ServiceImpl<OrdersDao, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 提交订单
     * @param orders
     * @param httpSession
     * @return
     */
    @Override
    //Orders(id=null, number=null, status=null, userId=null, addressBookId=1587690984750518274,
    // orderTime=null, checkoutTime=null, payMethod=1,amount=null, remark=多加饭, userName=null,
    // phone=null, address=null, consignee=null)
    public boolean submit(Orders orders, HttpSession httpSession) {
        //将用户ID存到Order里面
        User user = (User) httpSession.getAttribute("user");
        orders.setUserId(user.getId());
        User byId = userService.getById(user.getId());
        //用户名
        orders.setUserName(byId.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        //订单号(随机生成的id)
        long id = IdWorker.getId();
        orders.setNumber(String.valueOf(id));
        orders.setId(id);
        //将Order里面的购物车id查出来
//        LambdaQueryWrapper<ShoppingCart>wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(ShoppingCart::getUserId,user.getId());
//        List<ShoppingCart> list = shoppingCartService.list(wrapper);
        //用户的地址也查出来
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //地址
        orders.setAddress(addressBook.getDetail());
        //收件人
        orders.setConsignee(addressBook.getConsignee());
        //手机号
        orders.setPhone(addressBook.getPhone());
        //购物车的东西
        LambdaQueryWrapper<ShoppingCart>wrapper1=new LambdaQueryWrapper<>();
        wrapper1.eq(ShoppingCart::getUserId,user.getId());
        List<ShoppingCart> list1 = shoppingCartService.list(wrapper1);
        AtomicInteger amount=new AtomicInteger(0);
        List<OrderDetail>details=new ArrayList<>();
        for (ShoppingCart shoppingCart : list1) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(id);
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            //如果菜品的价格发送了变化
            if (shoppingCart.getDishId()!=null){
                Dish dish = dishService.getById(shoppingCart.getDishId());
                //如果购物车的商品已经停售了就返回错误
                if (dish.getStatus()==0){
                    return false;
                }
                BigDecimal dishprice = dish.getPrice().divide(BigDecimal.valueOf(100));
                BigDecimal shoppingCartAmount = shoppingCart.getAmount();
                if (!dishprice.equals(shoppingCartAmount)){
//                    shoppingCart.setAmount(dish.getPrice().divide(BigDecimal.valueOf(100)));
                    return false;
                }
            }
            //如果套餐的价格发生了变化
            if (shoppingCart.getSetmealId()!=null){
                Setmeal setmeal = setmealService.getById(shoppingCart.getSetmealId());
                if (setmeal.getStatus()==0){
                    return false;
                }
                if (!setmeal.getPrice().divide(BigDecimal.valueOf(100)).equals(shoppingCart.getAmount())){
//                    shoppingCart.setAmount(setmeal.getPrice().divide(BigDecimal.valueOf(100)));
                    return false;
                }
            }
            orderDetail.setAmount(shoppingCart.getAmount());
            details.add(orderDetail);
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
        }
        //订单明细的数据提交到订单明细表
        orderDetailService.saveBatch(details);
        //订单价格
        orders.setAmount(new BigDecimal(amount.get()));
        //将订单信息保存到订单表里面
        this.save(orders);
        //清空购物车
        shoppingCartService.remove(wrapper1);
        return true;
    }
}
